package com.gxa.meiye.admin.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.meiye.admin.service.IdCardService;
import com.gxa.meiye.admin.service.TherapistService;
import com.gxa.meiye.admin.utils.HttpUtils;

import com.gxa.meiye.admin.utils.TokenUtil;
import com.gxa.meiye.core.common.JsonResult;
import com.gxa.meiye.core.exception.BusinessException;
import com.gxa.meiye.core.pojo.domain.PayAccountInfo;
import com.gxa.meiye.core.pojo.domain.TherapistInfo;
import com.gxa.meiye.core.pojo.entity.IdCard;
import com.gxa.meiye.core.pojo.entity.Therapist;
import com.gxa.meiye.core.pojo.vo.ReqTherapistInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chen
 * @date 2022/7/19 10:05
 */
@Api(tags = "美疗师信息")
@Slf4j
@RestController
@RequestMapping("/mlstherapist")
public class TherapistController {

    private ObjectMapper objectMapper = new ObjectMapper();


    @Autowired
    private IdCardService idCardService;
    @Autowired
    private TherapistService therapistService;

    private String host = "https://qryidcard.market.alicloudapi.com";
    private String path = "/lundear/ckidcard";
    private String method = "GET";
    private String appcode = "1689750f95584841af32aa4ace25ad64";

    @Autowired
    private TokenUtil tokenUtil;

    @ApiOperation("查看我的信息")
    @GetMapping("/myMessage")
    @ResponseBody
    public JsonResult getMyMessage(ServletRequest request) throws JsonProcessingException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String token = httpRequest.getHeader("token");
        Map user = tokenUtil.getUserByToken(token);
        Integer id1 = (Integer)user.get("id");
        TherapistInfo therapistInfo = this.therapistService.queryMyMessage(id1);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("查询成功");
        if (therapistInfo==null){
            jsonResult.setMsg("没有对应的信息");
        }
        jsonResult.setData(therapistInfo);
        return jsonResult;
    }

    /**
     *
     * @param therapistInfo
     * @return
     */
    @ApiOperation("修改我的信息")
    @ResponseBody
    @PostMapping("updateMessage")
    public JsonResult updateMyMessage(ReqTherapistInfo therapistInfo) throws BusinessException {
        Therapist byId = this.therapistService.getById(therapistInfo.getId());
        if (therapistInfo.getIndividual_resume()!=null) {
            byId.setIndividualResume(therapistInfo.getIndividual_resume());
        }
        if (therapistInfo.getName()!=null) {
            byId.setName(therapistInfo.getName());
        }
        if (therapistInfo.getImages()!=null) {
            byId.setAvatar(therapistInfo.getImages());
        }
        boolean update = this.therapistService.updateById(byId);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setMsg("修改成功");
        jsonResult.setCode("200");
        if (update==false){
            jsonResult.setMsg("修改失败");
        }
        return jsonResult;
    }


    @ApiOperation("实名制信息")
    @ResponseBody
    @GetMapping("shiming")
    public JsonResult shiming(@NotEmpty(message = "名字不能为空") String name ,
                              @Validated
                              @Pattern(regexp = "/^[1-9]\\d{5}(18|19|20|(3\\d))\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$/") String idNumber,
                              Integer id) throws JsonProcessingException {
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("idcard", idNumber);
        querys.put("name", name);
        JsonResult jsonResult = new JsonResult();
        HashMap<String,String> map = new HashMap<>();
        IdCard idCard = new IdCard();
        idCard.setName(name);
        idCard.setIdcard_info(idNumber);
        idCard.setTherapist_id(id);
        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            String s = EntityUtils.toString(response.getEntity());
            String s1 = s.replace("{", "");
            String s2 = s1.replace("}", "");
            String s3 = s2.replace("\"","");
            String s4 = s3.replace("data:","");
            String[] strings = s4.split(",");
            for (int i = 0; i < strings.length; i++) {
                String[] split = strings[i].split(":");
                map.put(split[0],split[1]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonResult.setMsg(map.get("desc"));
        jsonResult.setCode(map.get("code"));
        String code = map.get("code");
        if (code .equals("0")){
            boolean save = this.idCardService.save(idCard);
            Therapist byId = this.therapistService.getById(id);
            byId.setRealNameVerification(1);
            boolean relname = this.therapistService.updateById(byId);
            if (save == false && relname == false){
                jsonResult.setCode("-200");
                jsonResult.setMsg("实名认证失败");
            }
            jsonResult.setMsg("实名制成功");
        }
        return jsonResult ;
    }

    @ApiOperation("查看我的实名制信息")
    @ResponseBody
    @GetMapping("/getMyRelName")
    public JsonResult getMyRelName(ServletRequest request) throws JsonProcessingException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String token = httpRequest.getHeader("token");
        Map user = tokenUtil.getUserByToken(token);
        Integer id = (Integer)user.get("id");
        //根据user的orgCode进行查询
        IdCard idCard = this.idCardService.queryByTherapistId(id);
        //log.info(idCard.toString());
        String idcard_info = idCard.getIdcard_info();
        idCard.setIdcard_info(this.ID_NumChange(idcard_info));
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("查询成功，你已经王成实名制认证");
        jsonResult.setData(idCard);
        if (idCard == null){
            jsonResult.setMsg("没有查到你的实名制信息，请完成实名制");
        }
        return jsonResult;
    }

    @ApiOperation("修改我的收款信息")
    @PostMapping("/updatePayInfo")
    public JsonResult updatePayInfo(@ApiParam(name = "name",value = "名子",type = "String")String name,
                                    @ApiParam(name = "account",value = "账号",type = "String")String account,
                                    ServletRequest request) throws JsonProcessingException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String token = httpRequest.getHeader("token");
        Map user = tokenUtil.getUserByToken(token);
        Integer id = (Integer)user.get("id");
        Integer integer = this.therapistService.updatePayInfo(name, account, id);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("修改成功");
        if (integer==0){
            jsonResult.setCode("-200");
            jsonResult.setMsg("修改失败");
        }
        return jsonResult;
    }

    @ApiOperation("查看我的收款信息")
    @GetMapping("/getPayInfo")
    public JsonResult getPayInfo(ServletRequest request) throws JsonProcessingException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String token = httpRequest.getHeader("token");
        Map user = tokenUtil.getUserByToken(token);
        Integer id = (Integer)user.get("id");
        PayAccountInfo payAccountInfo = this.therapistService.queryById(id);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("查询成功");
        jsonResult.setData(payAccountInfo);
        return jsonResult;
    }


    public String ID_NumChange(String idNum){
        char[] chars = idNum.toCharArray();
        for (int i = chars.length-1; i > 0 ; i--) {
            if (idNum.length()-1-i>3 && i>3){
                chars[i] = '*';
            }
        }
        return String.copyValueOf(chars);
    }


    @ApiOperation("查看我的项目的评价")
    @GetMapping("/getEvaluate")
    public JsonResult getEvaluate(ServletRequest request,
                                  Integer page,Integer size) throws JsonProcessingException {
        if (page<1){
            page = 1;
        }
        if (size<0){
            size = 10;
        }
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String token = httpRequest.getHeader("token");
        Map user = tokenUtil.getUserByToken(token);
        Integer id = (Integer)user.get("id");
        List<String> list = this.therapistService.getEvaluate(id, page, size);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("查询成功");
        jsonResult.setData(list);
        return jsonResult;
    }

    @ApiOperation("查看我的项目的评分")
    @GetMapping("/getGrade")
    public JsonResult getGrade(@ApiParam(name = "id",value = "项目的id",type = "Integer")Integer id){
        Integer total = this.therapistService.getTotal(id);
        HashMap<String, Object> map = new HashMap<>();
        map.put("total",total);
        List<Integer> grade = this.therapistService.getGrade(id);
        map.put("grade",grade);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("查询成功");
        jsonResult.setData(map);
        return jsonResult;
    }


}
